package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;
import com.bdqn.util.Constants;
import com.bdqn.util.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/user")
public class SysUserController {
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserService sysUserService;
    private static final Logger log = Logger.getLogger(SysUserController.class);
    @GetMapping("/list")
    public String list(Model model, @RequestParam(value = "queryRealName", required = false) String queryRealName, @RequestParam(value = "queryRoleId", required = false) Long queryRoleId, @RequestParam(value = "pageIndex", defaultValue = "1") Long pageIndex) {
        List<SysUser> userList = null;
        List<SysRole> sysRoles = null;
        try {
            //总数量
            long totalCount = sysUserService.count(queryRealName, queryRoleId);
            //总页数
            PageSupport page = new PageSupport();
            page.setPageSize(page.getPageSize());       // 设置一页显示数据量
            page.setTotalCount(totalCount);
            page.setCurrentPageNo(pageIndex);

            // 设置当前页数
            long totalPageCount = page.getTotalPageCount();

            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.page(queryRealName, queryRoleId, page);
            sysRoles = sysRoleService.getAll();
            page.setData(userList);

            model.addAttribute("userList", userList);  // 用户信息

            model.addAttribute("page", page); // 查询条件回显
            model.addAttribute("queryRealName", queryRealName); // 查询条件回显
            model.addAttribute("queryRoleId", queryRoleId);

            model.addAttribute("roleList", sysRoles);

        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/checkOldPwd",produces = {"application/json;charset=UTF-8"})
    public String getPwd(String oldPassword, HttpServletResponse response, HttpSession session) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        // 查询输入密码是否和数据库用户密码相同
        String account = sysUser.getAccount();
        int pwd = sysUserService.getPwd(oldPassword,account);
        Map<String,String> map = new HashMap<>();
        String result = "true";
        // 判断是否与旧密码相同 true:成功 false:失败
        if (pwd == 1){
            result = "true";
        }else {
            result = "false";
        }

        map.put("result",result);
        return JSON.toJSONString(map);
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/savePassword",produces = "text/html; charset=UTF-8")
    public String savePassword(String newPassword,HttpSession session,HttpServletResponse response) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        // 调用方法修改密码
        int iRet = sysUserService.savePassword(sysUser.getAccount(),newPassword);

        String result = null;
        if (iRet == 1){
            result = "<script>alert('修改密码成功！');window.location='http://localhost:8080/Spri_724_war_exploded/user/toUpdatePwd'</script>";
        }else{
            result = "<script>alert('修改密码失败！');window.location='http://localhost:8080/Spri_724_war_exploded/user/toUpdatePwd'</script>";
        }

        return result;
    }

    @GetMapping("/add")
    public String toAdd(Model model) {
        List<SysRole> sysRoles = null;
        sysRoles = sysRoleService.getAll();
        model.addAttribute("roleList", sysRoles);
        return "sysUser/add";
    }
    @GetMapping("/userExist")
    public String userExist(String account, Model model) {
        int exist = -1;
        boolean flag = sysUserService.userExist(account);
        if (flag) {
            exist = 1;
        }else {
            exist = 0;
        }
        return JSONObject.of("exist", exist).toString();
    }
    @PostMapping("/add")
    public String doAdd(HttpServletRequest request,HttpSession session,SysUser sysUser,MultipartFile idPic, MultipartFile workPic){
        SysUser loginUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        // 文件上传到服务器的真实位置
        sysUser.setCreatedUserId(loginUser.getId());
        sysUser.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        // 文件上传到服务器的真实位置 C:\Service\apache-tomcat-9.0.91\webapps\724\web\statics\...
        String uploadPath = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);

        Map<String, String> msg = new HashMap<>();
        // 身份证照片上传
        if (idPic != null) {
            // 提取文件上传的方法
            String idPicPath = multipartFileUpload(uploadPath, idPic, msg);
            // Web访问的路径（不是文件上传的磁盘位置）
            if (idPicPath == null) {
                String uploadFileError = msg.get("uploadFileError");
                request.setAttribute("idPicUploadError", uploadFileError);
                return "sysUser/add";
            }
            // 设置身份证照片路径
            sysUser.setIdPicPath(idPicPath);
        }
        // 工作证照片上传
        if (workPic != null) {
            // 提取文件上传的方法
            String workPicPath = multipartFileUpload(uploadPath, workPic, msg);
            // Web访问的路径（不是文件上传的磁盘位置）
            if (workPicPath == null) {
                String uploadFileError = msg.get("uploadFileError");
                request.setAttribute("workPicUploadError", uploadFileError);
                return "sysUser/add";
            }
            // 设置工作证照片路径
            sysUser.setWorkPicPath(workPicPath);
        }
        boolean sAdd =  sysUserService.add(sysUser);
        if (sAdd) {
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }

    /**
     * 多部件文件上传（错误信息临时保存在request作用域uploadFileError属性中）
     *
     * @return 成功返回文件上传地址，返回null表示文件上传失败
     */
    public synchronized String multipartFileUpload(String uploadPath, MultipartFile multipartFile, Map<String, String> msg) {
        String uploadFilePath = null; // 文件上传地址，返回null表示文件上传失败
        // 定义文件存放目录
        log.debug("上传文件路径：" + uploadPath);

        if (!multipartFile.isEmpty()) {
            // 获取上传的文件信息
            String originalFile = multipartFile.getOriginalFilename(); // 原文件名称
            log.debug("原文件名称为：" + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile); // 原文件后缀
            log.debug("原文件后缀为：" + prefix);
            long fileSize = multipartFile.getSize(); // 原文件大小
            log.debug("上传文件大小：" + fileSize);

            // 判断上传的文件是否符合要求
            if (fileSize > Constants.MAX_FILE_SIZE) { // 上传文件大小不能超过500KB
                msg.put("uploadFileError", " * 上传文件大小不得超过 5MB");
                return uploadFilePath;
            }
            if (prefix != null && !(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("pneg"))) {
                msg.put("uploadFileError", " * 上传文件格式只能是jpg、jpeg、png、pneg");
                return uploadFilePath;
            }

            // 确定文件存储名称
            String fileName = System.nanoTime() + RandomUtils.nextInt(1000) + "_Personal." + prefix;
            log.debug("新生成的文件名为：" + fileName);

            // 将上传的文件保存到目标位置
            File targetFile = new File(uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs(); // 如果目录不存在则生成目录
            }
            // 保存文件
            try {
                // 存储物理地址 + 生成的文件名称
                multipartFile.transferTo(new File(targetFile, fileName));
            } catch (IOException e) {
                e.printStackTrace();
                msg.put("uploadFileError", " * 文件上传失败！");
                return uploadFilePath;
            }
            // 文件上传完成就可以拿到地址
            // /statics/upload/98020913201542_Personal.jpg
            uploadFilePath = File.separator + Constants.UPLOAD_PATH + File.separator + fileName;
        }

        // 返回文件上传成功后的地址，失败时返回null，并且将失败信息记录到
        return uploadFilePath;
    }
    /**
     * Ajax查询数据展示
     *
     * @param userId 用户ID
     * @return JSON格式的对象数据
     */
    @ResponseBody
    @GetMapping("/{userId}/view")
    public String view(@PathVariable("userId") Long userId) {
        // 调用业务逻辑层根据ID查询用户
        SysUser sysUser = sysUserService.getById(userId);
        return JSONObject.toJSONString(sysUser);
    }
    // 退出
    @RequestMapping("/logout")
    public String tui(HttpSession session){
        session.removeAttribute("USER_SESSION");
        session.invalidate();
        return "login";
    }

    /**
     * Ajax异步删除用户
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @DeleteMapping("/del/{userId}")
    public String del(HttpSession session, @PathVariable("userId") Long userId) {
        String uploadPath = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);
        int result = 0;
        try {
            result = sysUserService.del(uploadPath, userId); // -1表示不存在，1表示成功，0表示失败
        } catch (RuntimeException e) {
            result = 0;
            log.error(e.getMessage());
        }
        return JSONObject.of("delResult", result == -1 ? "notexist" : result == 1 ? "true" : "false").toString();
    }
}
